package com.ysd.lis.controller.lab;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.annotation.MainInfoLog;
import com.ysd.lis.aspect.OperationType;
import com.ysd.lis.aspect.SysEventLog;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabProcessSet;
import com.ysd.lis.entity.lab.LabReqMain;
import com.ysd.lis.mapper.lab.LabReqMainMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.AddLabMaininfo;
import com.ysd.lis.request.LabMaininfoPageDto;
import com.ysd.lis.request.LabReqAdditionsDto;
import com.ysd.lis.request.PrintBarcodeDto;
import com.ysd.lis.request.lab.LabMaininfoCreateOrUpdateDto;
import com.ysd.lis.request.lab.LabReqMainChangeWkflwParam;
import com.ysd.lis.request.lab.LabReqMainDto;
import com.ysd.lis.request.lab.LabReqMainReceptionParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.bak.LabReqMainBakService;
import com.ysd.lis.service.lab.LabReqMainService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 检验申请主表 前端控制器
 * </p>
 *
 * @author HuiXing
 * @since 2023-12-26
 */
@RestController
@RequestMapping("/lab/reqMain")
public class LabReqMainController extends BaseController {
    @Autowired
    LabReqMainService reqMainService;

    @Autowired
    LabReqMainBakService reqMainBakService;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    LabReqMainMapper labReqMainMapper;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    //根据条码号获取申请信息
    @ApiOperation("获取取申请信息")
    @GetMapping("/getReqMainByReqNo")
    public Result getReqMain(LabReqMain reqMain) throws JsonProcessingException {
        return reqMainService.getReqMainByReqNo(reqMain);
    }

    @ApiOperation("分页获取采集信息列表")
    @GetMapping("/findLabReqMainPageListByState")
    public Result findLabReqMainPageListByState(LabMaininfoPageDto maininfoPageDto) {
        return reqMainService.findLabReqMainPageListByState(maininfoPageDto);
    }

    @ApiOperation("分页获取历史签收列表")
    @GetMapping("/findLabReqMainReHistoryPage")
    public Result findLabReqMainCollectionHistory(LabMaininfoPageDto maininfoPageDto) {
        return reqMainBakService.findLabReqMainReHistoryPage(maininfoPageDto);
    }

    @ApiOperation("分页获取历史退费列表")
    @GetMapping("/findLabReqMainReturnFeePage")
    public Result findLabReqMainReturnFeePage(LabMaininfoPageDto maininfoPageDto) {
        Page<LabReqMain> page = new Page<LabReqMain>();
        page.setCurrent(maininfoPageDto.getPageIndex());
        page.setSize(maininfoPageDto.getPageSize());
        SysUser sysUser = RedisUserManager.getUser();
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);
        queryWrapper.selectAs("pros", LabProcessSet::getDisplayColor, LabReqMain::getDisplayColor);
        queryWrapper.selectAs("pros", LabProcessSet::getNodeName, LabReqMain::getStateNa);
        queryWrapper.leftJoin(LabProcessSet.class, "pros", p -> p.eq(LabProcessSet::getCode, LabReqMain::getState).eq(LabProcessSet::getDelFlag, 0));

        queryWrapper.eq(LabReqMain::getDelFlag, 0);
        String state = maininfoPageDto.getState();
        if (ToolsUtils.isNotEmpty(state)) {
            if("0".equals(state)){
                queryWrapper.and(warrp->warrp.eq(LabReqMain::getIsCancel,0).or().isNull(LabReqMain::getIsCancel));
            }else {
                queryWrapper.eq(LabReqMain::getIsCancel, Integer.valueOf(state));
            }
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getOrgId())) {
            queryWrapper.eq(SysEventLog::getOrgId, sysUser.getOrgId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqNo())) {
            queryWrapper.like(LabReqMain::getReqNo, maininfoPageDto.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatId())) {
            queryWrapper.like(LabReqMain::getPatId, maininfoPageDto.getPatId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNa())) {
            queryWrapper.like(LabReqMain::getPatNa, maininfoPageDto.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNo())) {
            queryWrapper.like(LabReqMain::getPatNo, maininfoPageDto.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeE())) {
            queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
            queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSignTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSignTimeE())) {
            queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeS()).getTime()));
            queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSignTimeE()).getTime()));
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getReqTimeE())) {
            queryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getReqTimeS()).getTime()));
            queryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(maininfoPageDto.getReqTimeE()).getTime()));
        }
        queryWrapper.orderByDesc(LabReqMain::getReqTime);
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        Page<LabReqMain> reqPageList = labReqMainMapper.selectPage(page, queryWrapper);

        for (LabReqMain reqMain : (List<LabReqMain>) reqPageList.getRecords()) {
            if (StringUtils.isNotBlank(reqMain.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(reqMain.getSex())).findFirst().ifPresent(stringObjectMap -> reqMain.setSexNa((String) stringObjectMap.get("name")));
            }
        }
        return Result.succ(1, "查询成功", reqPageList);
    }

    //根据条码号退费
    @ApiOperation("根据条码号退费")
    @PostMapping("/returnLabFeeByReqNo")
    public Result returnLabFeeByReqNo(@RequestBody LabReqMain labReqMain) {
        SysUser sysUser = RedisUserManager.getUser();
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        //标本签收
        if (CollectionUtils.isNotEmpty(collect)) {
            /*发布报告相关*/
            for (String webUrl : collect) {
                //调用修改状态接口
                Map<String, Object> updateMap = new HashMap<>();
                updateMap.put("reqNo", labReqMain.getReqNo());
                updateMap.put("username", sysUser.getUsername());
                updateMap.put("realname", sysUser.getRealname());
                updateMap.put("orgId",sysUser.getOrgId());
                //菏泽三院退费接口
                String returnFeeUrl = webUrl + "/public/barcodeDelReturnFee";
                String update11 = HttpUtil.createPost(returnFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
            }
        }
        LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabReqMain::getReqNo, labReqMain.getReqNo())
                .eq(LabReqMain::getDelFlag, 0);
        LabReqMain labReqMain1 = new LabReqMain();
        labReqMain1.setIsCancel(1);
        labReqMain1.setCancelDoctor(sysUser.getUsername());
        labReqMain1.setCancelDoctorNa(sysUser.getRealname());
        labReqMain1.setCancelTime(new Timestamp(System.currentTimeMillis()));
        labReqMain1.setCancelReason(labReqMain.getCancelReason());
        boolean update = reqMainService.update(labReqMain1, lambdaQueryWrapper);
        if(update){
            return Result.succ(1,"退费成功","");
        }
        return Result.fail("退费失败");
    }
    @ApiOperation("分页获取采集信息列表")
    @GetMapping("/findLabReqMainPageListBySample")
    public Result findLabReqMainPageListBySample(LabMaininfoPageDto maininfoPageDto) {
        return reqMainService.findLabReqMainPageListBySample(maininfoPageDto);
    }

    @ApiOperation("查询检验申请")
    @PostMapping("/findLabReqMainPageList")
    public Result findLabReqMainPageList(@RequestBody LabMaininfoPageDto maininfoPageDto) {
        return reqMainService.findLabReqMainPageList(maininfoPageDto);
    }

    @ApiOperation("查询检验申请(历史数据)")
    @PostMapping("/findHisStoryLabReqMainPageList")
    public Result findHisStoryLabReqMainPageList(@RequestBody LabMaininfoPageDto maininfoPageDto) {
        return reqMainBakService.findHisStoryLabReqMainPageList(maininfoPageDto);
    }


    @ApiOperation("分页查询检验申请")
    @GetMapping("/findLabReqMainList")
    public Result findLabReqMainList(LabReqMainDto labReqMain) {
        return reqMainService.findLabReqMainList(labReqMain);
    }

    @ApiOperation("分页查询检验申请和上机记录")
    @GetMapping("/findLabReqMainOrMainfoList")
    public Result findLabReqMainOrMainfoList(LabReqMainDto labReqMain) {
        return reqMainBakService.findLabReqMainOrMainfoList(labReqMain);
    }
    @ApiOperation("分页查询检验申请和上机记录")
    @GetMapping("/exportOrMainInfoExcel")
    public Result exportOrMainInfoExcel( LabReqMainDto labReqMain) {
      return  reqMainBakService.exportOrMainInfoExcel(labReqMain);
    }

    @ApiOperation("分页查询检验申请")
    @GetMapping("/exportReqExcel")
    public Result exportReqExcel( LabReqMainDto labReqMain) {
      return  reqMainBakService.exportReqExcel(labReqMain);
    }

    @ApiOperation("查询Tat申请信息")
    @GetMapping("/findLabTatReqMainList")
    public Result findLabTatReqMainList(LabReqMainDto labReqMain) {
        return reqMainService.findLabTatReqMainList(labReqMain);
    }

    @ApiOperation("无查询检验申请")
    @GetMapping("/findMainList")
    public Result findMainList(LabReqMainDto labReqMain) {
        return reqMainService.findMainList(labReqMain);
    }

    @ApiOperation("无查询检验申请和收费明细")
    @GetMapping("/findReqMainAndDetailList")
    public Result findReqMainAndDetailList(LabReqMainDto labReqMain) throws JsonProcessingException {
        return reqMainService.findReqMainAndDetailList(labReqMain);
    }

    //根据条码号获取申请信息
    @ApiOperation("标本采集信息更改")
    @PostMapping("/createSamplingDetail")
    public Result createSamplingDetail(@RequestBody LabReqMain labReqMain) throws JsonProcessingException {
        return reqMainService.createSamplingDetail(labReqMain);
    }

    //根据条码号获取申请信息
    @ApiOperation("标本接收信息更改")
    @PostMapping("/createCollectionDetail")
    public Result createCollectionDetail(@RequestBody LabReqMain labReqMain) throws JsonProcessingException {
        return reqMainService.createCollectionDetail(labReqMain);
    }

    @ApiOperation("条码信息查询")
    @PostMapping("/barcodePrintQuery")
    public Result barcodePrintQuery(@RequestBody PrintBarcodeDto dto) {
        return reqMainService.barcodePrintQuery(dto);
    }

    @ApiOperation("条码重打")
    @GetMapping("/barcodeReprint")
    public Result barcodeReprint(@RequestParam("ids") List<String> ids) {
        return reqMainService.barcodeReprint(ids);
    }


    @ApiOperation("获取申请附加信息")
    @GetMapping("/findLabReqAdditions")
    public Result findLabReqAdditions(String reqNo) {
        return reqMainService.findLabReqAdditions(reqNo);
    }

    @ApiOperation("通过reqNo获取申请信息")
    @GetMapping("/findReqMainByReqNo")
    public Result findReqMainByReqNo(String reqNo) {
        return reqMainService.findReqMainByReqNo(reqNo);
    }

    @ApiOperation("绑定申请附加信息")
    @GetMapping("/addReqAdditions")
    public Result addReqAdditions(LabReqAdditionsDto labReqAdditionsDto) {
        return reqMainService.addReqAdditions(labReqAdditionsDto);
    }

    @ApiOperation("删除申请附加信息")
    @GetMapping("/deleteReqAdditions")
    public Result deleteReqAdditions(LabReqAdditionsDto labReqAdditionsDto) {
        return reqMainService.deleteReqAdditions(labReqAdditionsDto);
    }

    @ApiOperation("微生物标本签收")
    @PostMapping("/bacReqReception")
    public Result bacReqReception(@RequestBody LabReqMainReceptionParam input) {
        return reqMainService.bacReqReception(input);
    }

    @ApiOperation("微生物接收时创建申请")
    @PostMapping("/bacCreateReqMain")
    public Result bacCreateReqMain(@RequestBody LabReqMain reqMain) {
        return reqMainService.bacCreateReqMain(reqMain);
    }
    @ApiOperation("绿色通道生成申请信息")
    @PostMapping("/addBatchReqMainAndDetail")
    public Result addBatchReqMainAndDetail(@RequestBody LabReqMain reqMain) {
        return reqMainService.addBatchReqMainAndDetail(reqMain);
    }

    @ApiOperation("微生物接收时更新申请")
    @PostMapping("/bacUpdateReqMain")
    public Result bacUpdateReqMain(@RequestBody LabReqMain reqMain) {
        return reqMainService.bacUpdateReqMain(reqMain);
    }

    @ApiOperation("微生物接收时更新申请并重新计算应用方案、培养基")
    @PostMapping("/bacUpdateReqMainWithReset")
    public Result bacUpdateReqMainWithReset(@RequestBody LabReqMain reqMain) {
        return reqMainService.bacUpdateReqMainWithReset(reqMain);
    }

    @ApiOperation("微生物签收:加载首选方案")
    @GetMapping("/findDefaultWkflwForBacReception")
    public Result findDefaultWkflwForBacReception(LabReqMainReceptionParam input) {
        return reqMainService.findDefaultWkflwForBacReception(input);
    }

    @ApiOperation("微生物签收:切换首选方案")
    @PostMapping("/changeDefaultWkflwForBacReception")
    public Result changeDefaultWkflwForBacReception(@RequestBody LabReqMain reqMain) {
        return reqMainService.changeDefaultWkflwForBacReception(reqMain);
    }

    @ApiOperation("微生物签收:加载备选方案")
    @GetMapping("/findSecondWkflwForBacReception")
    public Result findSecondWkflwForBacReception(LabReqMainReceptionParam input) {
        return reqMainService.findSecondWkflwForBacReception(input);
    }

    @ApiOperation("微生物签收:切换备选方案")
    @PostMapping("/changeSecondWkflwForBacReception")
    public Result changeSecondWkflwForBacReception(@RequestBody LabReqMainChangeWkflwParam input) {
        return reqMainService.changeSecondWkflwForBacReception(input);
    }

    @ApiOperation("微生物签收:获取申请列表")
    @GetMapping("/findLabReqMainListForBacReception")
    public Result findLabReqMainListForBacReception(LabReqMainReceptionParam input) {
        return reqMainService.findLabReqMainListForBacReception(input);
    }

    @ApiOperation("微生物签收:删除签收申请状态")
    @PostMapping("/deleteBacReqReception")
    public Result deleteBacReqReception(@RequestBody LabReqMain reqMain) {
        return reqMainService.deleteBacReqReception(reqMain);
    }


    @ApiOperation("新增")
    @PostMapping("/addReqMain")
    public Result addReqMain(@RequestBody LabReqMain reqMain) {
        return reqMainService.addReqMain(reqMain);
    }

    @ApiOperation("查询")
    @GetMapping("/findReqMainList")
    public Result findReqMainList(LabReqMainDto param) {
        return reqMainService.findReqMainList(param);
    }

    @ApiOperation("查询")
    @GetMapping("/findReqMainAndDetail")
    public Result findReqMainAndDetail(LabReqMainDto param) {
        return reqMainService.findReqMainAndDetail(param);
    }

    @ApiOperation("新增")
    @PostMapping("/updateReqMain")
    public Result updateReqMain(@RequestBody LabReqMain reqMain) {
        return reqMainService.updateReqMain(reqMain);
    }


    @ApiOperation("删除")
    @PostMapping("/deleteReqMainById")
    public Result deleteReqMainById(@RequestBody LabReqMain reqMain) {
        return reqMainService.deleteReqMainById(reqMain);
    }

    @ApiOperation("申请审核")
    @PostMapping("/batchReqMainApprove")
    public Result batchReqMainApprove(@RequestBody LabReqMainDto dto) {
        return reqMainService.batchReqMainApprove(dto);
    }

    @ApiOperation("申请审核")
    @PostMapping("/cancelReqMainApprove")
    public Result cancelReqMainApprove(@RequestBody LabReqMainDto dto) {
        return reqMainService.cancelReqMainApprove(dto);
    }

    @ApiOperation("新增")
    @PostMapping("/updateReqMainAndDetail")
    public Result updateReqMainAndDetail(@RequestBody LabReqMain reqMain) {
        return reqMainService.updateReqMainAndDetail(reqMain);
    }

    @ApiOperation("申请闭环展示")
    @GetMapping("/findLabReqMainClosedLoopInfo")
    public Result findLabReqMainClosedLoopInfo(String reqNo) {
        return reqMainService.findLabReqMainClosedLoopInfo(reqNo);
    }

    @ApiOperation("申请闭环展示")
    @GetMapping("/findLabReqMainTatInfo")
    public Result findLabReqMainTatInfo(String reqNo) {
        return reqMainService.findLabReqMainTatInfo(reqNo);
    }

    @ApiOperation("作废标本")
    @GetMapping("/cancelReqMain")
    public Result cancelReqMain(String reqNo) throws JsonProcessingException {
        return reqMainService.cancelReqMain(reqNo);
    }

    @ApiOperation("扫码上机")
    @PostMapping("/insertMaininfoByReqNo")
    @MainInfoLog(operationType = OperationType.INSERT, module = "检验报告", content = "新增标本信息", businessName = "mainInfo")
    public Result insertMaininfoByReqNo(@RequestBody AddLabMaininfo labReqMain) throws JsonProcessingException {
        return reqMainBakService.insertMaininfoByReqNo(labReqMain);
    }

    @ApiOperation("批量扫码上机")
    @PostMapping("/insertMaininfo")
    public Result insertMaininfo(@RequestBody LabMaininfo labMaininfo) throws JsonProcessingException {
        return reqMainBakService.insertMaininfo(labMaininfo);
    }



    @ApiOperation("修改上机信息")
    @MainInfoLog(operationType = OperationType.UPDATE, module = "检验报告", content = "修改标本信息", businessName = "mainInfo")
    @PostMapping("/updateMaininfo")
    public Result updateMaininfo(@RequestBody LabMaininfoCreateOrUpdateDto input) throws JsonProcessingException {
        return reqMainBakService.updateMaininfo(input);
    }

}
